import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Row, Col, Statistic, Divider, Typography, Spin, DatePicker } from 'antd';
import { 
  UserOutlined, 
  ShoppingCartOutlined, 
  HomeOutlined, 
  CalendarOutlined, 
  CreditCardOutlined,
  GiftOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import { request } from 'umi';
import { Line, Pie, Column } from '@ant-design/charts';
import moment from 'moment';
import styles from './index.less';

const { Title, Paragraph } = Typography;
const { RangePicker } = DatePicker;

// 获取数据统计
const fetchStatistics = async () => {
  return request('/api/v1/statistics/overview', {
    method: 'GET',
  });
};

// 获取订单统计数据
const fetchOrderStats = async (params) => {
  return request('/api/v1/order/statistics', {
    method: 'GET',
    params,
  });
};

const StatisticPage = () => {
  const [loading, setLoading] = useState(true);
  const [statistics, setStatistics] = useState({
    userCount: 0,
    orderCount: 0,
    venueCount: 0,
    bookingCount: 0,
    totalRevenue: 0,
    couponCount: 0,
    todayOrders: 0,
    todayAmount: 0,
    pendingOrders: 0
  });
  const [orderStatusData, setOrderStatusData] = useState([]);
  const [paymentData, setPaymentData] = useState([]);
  const [orderTrend, setOrderTrend] = useState([]);

  useEffect(() => {
    fetchData();
  }, []);

  // 获取所有统计数据
  const fetchData = async () => {
    try {
      setLoading(true);
      // 获取概览数据
      const overviewRes = await fetchStatistics();
      if (overviewRes.success) {
        setStatistics(overviewRes.data || {});
        
        // 如果有订单趋势数据，则设置
        if (overviewRes.data?.orderTrend) {
          setOrderTrend(overviewRes.data.orderTrend);
        }
      }

      // 获取订单详细统计
      const orderStatsRes = await fetchOrderStats();
      if (orderStatsRes.success) {
        // 设置订单状态分布数据
        if (orderStatsRes.data?.statusData) {
          const statusData = orderStatsRes.data.statusData.map(item => ({
            type: getOrderStatusName(item.status),
            value: item.count
          }));
          setOrderStatusData(statusData);
        }

        // 设置支付方式分布数据
        if (orderStatsRes.data?.paymentTypeData) {
          const paymentData = orderStatsRes.data.paymentTypeData.map(item => ({
            type: getPaymentTypeName(item.payment_type),
            value: item.count
          }));
          setPaymentData(paymentData);
        }
      }
    } catch (error) {
      console.error('获取统计数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取订单状态名称
  const getOrderStatusName = (status) => {
    const statusMap = {
      1: '待支付',
      2: '已支付',
      3: '已完成',
      4: '已取消',
      5: '已退款'
    };
    return statusMap[status] || `未知状态(${status})`;
  };

  // 获取支付方式名称
  const getPaymentTypeName = (type) => {
    const typeMap = {
      1: '微信支付',
      2: '支付宝',
      3: '余额支付',
      4: '线下支付'
    };
    return typeMap[type] || `其他支付方式(${type})`;
  };

  // 饼图配置
  const pieConfig = {
    appendPadding: 10,
    data: orderStatusData,
    angleField: 'value',
    colorField: 'type',
    radius: 0.8,
    label: {
      type: 'outer',
      content: '{name} {percentage}',
    },
    interactions: [{ type: 'pie-legend-active' }, { type: 'element-active' }],
  };

  // 支付方式饼图配置
  const paymentPieConfig = {
    appendPadding: 10,
    data: paymentData,
    angleField: 'value',
    colorField: 'type',
    radius: 0.8,
    label: {
      type: 'outer',
      content: '{name} {percentage}',
    },
    interactions: [{ type: 'pie-legend-active' }, { type: 'element-active' }],
  };

  // 订单趋势图配置
  const lineConfig = {
    data: orderTrend,
    xField: 'date',
    yField: 'value',
    seriesField: 'type',
    smooth: true,
    animation: {
      appear: {
        animation: 'path-in',
        duration: 1000,
      },
    },
  };

  return (
    <PageContainer>
      <Card loading={loading}>
        <Title level={2} style={{ textAlign: 'center', marginBottom: 24 }}>
          系统信息统计
        </Title>
        
        <Row gutter={[24, 24]}>
          <Col xs={24} sm={12} md={8}>
            <Card bordered={false} className={styles.statisticCard}>
              <Statistic 
                title="会员数量" 
                value={statistics.userCount} 
                prefix={<UserOutlined />} 
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={8}>
            <Card bordered={false} className={styles.statisticCard}>
              <Statistic 
                title="总订单数" 
                value={statistics.orderCount} 
                prefix={<ShoppingCartOutlined />} 
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={8}>
            <Card bordered={false} className={styles.statisticCard}>
              <Statistic 
                title="场地数量" 
                value={statistics.venueCount} 
                prefix={<HomeOutlined />} 
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={8}>
            <Card bordered={false} className={styles.statisticCard}>
              <Statistic 
                title="门店数量" 
                value={statistics.bookingCount} 
                prefix={<CalendarOutlined />} 
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={8}>
            <Card bordered={false} className={styles.statisticCard}>
              <Statistic 
                title="总收入(元)" 
                value={(statistics.totalRevenue / 100).toFixed(2)} 
                precision={2} 
                prefix={<CreditCardOutlined />} 
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={8}>
            <Card bordered={false} className={styles.statisticCard}>
              <Statistic 
                title="优惠券发放数" 
                value={statistics.couponCount} 
                prefix={<GiftOutlined />} 
              />
            </Card>
          </Col>
        </Row>

        <Divider orientation="left">今日数据</Divider>
        
        <Row gutter={[24, 24]}>
          <Col xs={24} sm={12} md={8}>
            <Card bordered={false} className={styles.todayCard}>
              <Statistic 
                title="今日订单数" 
                value={statistics.todayOrders} 
                valueStyle={{ color: '#3f8600' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={8}>
            <Card bordered={false} className={styles.todayCard}>
              <Statistic 
                title="今日收入(元)" 
                value={(statistics.todayAmount / 100).toFixed(2)} 
                precision={2}
                valueStyle={{ color: '#3f8600' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} md={8}>
            <Card bordered={false} className={styles.todayCard}>
              <Statistic 
                title="待处理订单" 
                value={statistics.pendingOrders} 
                valueStyle={{ color: '#cf1322' }}
                prefix={<ExclamationCircleOutlined />}
              />
            </Card>
          </Col>
        </Row>
        
        <Divider orientation="left">数据分析</Divider>
        
        <Row gutter={[24, 24]}>
          <Col xs={24} md={12}>
            <Card title="订单状态分布" bordered={false}>
              {orderStatusData.length > 0 ? (
                <Pie height={300} {...pieConfig} />
              ) : (
                <div className={styles.noData}>暂无数据</div>
              )}
            </Card>
          </Col>
          <Col xs={24} md={12}>
            <Card title="支付方式分布" bordered={false}>
              {paymentData.length > 0 ? (
                <Pie height={300} {...paymentPieConfig} />
              ) : (
                <div className={styles.noData}>暂无数据</div>
              )}
            </Card>
          </Col>
          <Col xs={24}>
            <Card title="订单趋势分析" bordered={false}>
              <Line height={300} {...lineConfig} />
            </Card>
          </Col>
        </Row>
        
        <Divider />
        
        <Paragraph style={{ textAlign: 'center' }}>
          数据更新时间: {moment().format('YYYY-MM-DD HH:mm:ss')}
        </Paragraph>
      </Card>
    </PageContainer>
  );
};

export default StatisticPage;